# -*- coding: utf-8 -*-

'''eof
name:工商注册信息-生产经营地址变更
code:MR_OperationAddress
tableName:
columnName:
groups:烟商基本资质
dependencies:EG_LOAN
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import pandas as pd
from datetime import datetime
import json
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')


def format_data():
    try:
        clean = json.loads(EG_LOAN[0]['data'])['content']['srcData'][0]['ZBPT_BGXX_CLEAN']
        bgxx = clean["results"]
        return bgxx if isinstance(bgxx, list) and len(bgxx) > 0 else [{}]
    except:
        return [{}]


def get_date_list(month):
    try:
        now = datetime.now()
        month_time = now + relativedelta(months=-month)
        aaa = [(month_time + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-1, 0]]
        return aaa
    except:
        return None


# 统一转成年月日字符串，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def MR_OperationAddress():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    try:
        bgxx_list = format_data()
        date_list = get_date_list(0)
        count_list = set()

        if bgxx_list == [{}]:
            return u'缺失值'
        else:
            if len(bgxx_list) >= 1:
                for i in bgxx_list:
                    if i.get("change_date") not in null_type_list and date_format(i.get("change_date")) \
                            not in null_type_list and i.get("change_key") not in null_type_list:
                        change_date = date_format(i.get("change_date"))
                        before = i['content_before_change'] if i.get('content_before_change') is not None else ''
                        after = i['content_after_change'] if i.get('content_after_change') is not None else ''
                        if date_list[0] < change_date <= date_list[1] and i.get("change_key") == 'address':
                            count_list.add(change_date + before + "|" + after)
                        else:
                            count_list.add(0)
                    else:
                        count_list.add(None)
                count_not_none = filter(lambda x: x is not None, count_list)
                if len(count_not_none) < 1:
                    return u'缺失值'
                else:
                    count_not_zero = filter(lambda x: x != 0, count_not_none)
                    return len(count_not_zero)
            else:
                return 0
    except:
        return u'缺失值'


result = MR_OperationAddress()